package com.meida.student.app.user.handler;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.handler.SendEmailCodeHandler;
import com.meida.common.base.module.EmailInfo;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.RedisUtils;
import com.meida.module.user.client.entity.AppUser;
import com.meida.module.user.provider.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zyf
 */
@Component
public class SchoolAuthHandler implements SendEmailCodeHandler {
    @Autowired
    private RedisUtils redisUtils;


    @Autowired
    private AppUserService appUserService;

    @Override
    public EmailInfo initEmailInfo(EmailInfo emailInfo) {
        emailInfo.setSetSubject("留同学学校认证验证码");
        emailInfo.setFrom("留同学");
        return emailInfo;
    }

    /**
     * 校验通过后保存学校认证信息
     *
     * @param email
     * @param params
     * @return
     */
    @Override
    public ResultBody validSuccess(String email, EntityMap params) {
        Long userId = OpenHelper.getUserId();
        String schoolId = params.get("schoolId");
        AppUser appUser = appUserService.getUserById(userId);
        appUser.setSchoolId(schoolId);
        appUser.setEmail(email);
        appUser.setSchoolAuth(1);
        bindXk(schoolId, userId);
        appUserService.updateById(appUser);
        return ResultBody.ok("认证通过");
    }

    /**
     * 绑定选课助手require('vue-jeecg-plugs/packages/utils')
     */
    private void bindXk(String schoolId, Long userId) {
        EntityMap map = redisUtils.getConfigMap("XUANKE");
        String access_token = FlymeUtils.getString(map.get("accessToken"), "4u2jFQom3aPzxoaSDQHrVsC0bTWVngsRMYXukfILfoKhP3hrs07aaXftdccU1BDL");
        ApiAssert.isNotEmpty("accessToken未配置", access_token);
        HttpRequest.post("https://xuankezhushou.herokuapp.com/api/users/bindLtxId")
                .form("user_id", userId)
                .form("ltx_school_id", schoolId)
                .header("Authorization", access_token)
                .timeout(8000)
                .execute();

    }
}
